<template>
  <div>
    <el-button type="danger" @click="handleAddUserClick">添加用户</el-button>

    <el-table
      :data="tableData"
      style="width: 100%">
      <el-table-column
        prop="index"
        label="日期"
        width="180">
      </el-table-column>
      <el-table-column
        label="用户头像"
        width="180"
      >
        <template v-slot="scope">
          <img :src="`http://localhost:3000/uploads/${scope.row.filename}`" width="50" height="50" alt="">
        </template>
      </el-table-column>
      <el-table-column
        prop="username"
        label="用户名">
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleRemoveClick(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      :current-page="currentPage+1"
      @current-change="handlePageChange"
    >
    </el-pagination>

    <el-dialog :title="dialogType === 'add' ? '添加用户' : '编辑用户'" :visible.sync="dialogFormVisible">
      <el-form :model="form" ref="userForm" :rules="rules">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>        
        <el-form-item v-if="dialogType === 'add'" label="密码" :label-width="formLabelWidth" prop="password">
          <el-input type="password" v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="上传头像" :label-width="formLabelWidth">
          <Upload
            ref="upload"
            :filename.sync="filename"
          ></Upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmitClick">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Upload from './Upload'
export default {
  components: {
    Upload
  },

  data() {
    return {
      tableData: [],
      tableDataList: [],

      dialogTableVisible: false,
      dialogFormVisible: false,
      form: {
        id: '',
        username: '',
        password: '',
        filename: ''
      },
      
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 6, message: '长度在 6 个字符以上', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '且长度在 6 个字符以上', trigger: 'blur' }
        ],
      },
      formLabelWidth: '120px',

      total: 0,

      currentPage: 0,
      pageSize: 2,

      dialogType: 'add',

      filename: ''
    }
  },

  methods: {
    handleAddUserClick() {
      this.dialogFormVisible = true
      this.dialogType = 'add'
      this.form.username = ''
      this.form.password = ''
    },

    handlePageChange(page) {
      this.currentPage = page - 1
      this.filterData()
    },

    handleEdit(index, row) {
      this.dialogFormVisible = true
      this.dialogType = 'edit'
      let { username, id } = row
      this.form.username = username
      this.form.id = id
    },

    filterData() {
      // 判断是否是最后一页，最后一条被删除
      let pageCount = Math.ceil(this.total / this.pageSize)

      console.log(this.currentPage, pageCount)

      if (this.currentPage >= pageCount) {
        this.currentPage--
      }

      let data = this.tableDataList
      let start = this.currentPage * this.pageSize
      let end = start + this.pageSize
      
      let tableData = data.slice(start, end).map((v,i) => ({
        id: v._id,
        index: i + 1,
        username: v.username,
        filename: v.filename
      }))
      
      this.tableData = tableData
    },

    handleSucc(result) {
      let msg = result.data.data.msg
      if (result.data.ret) {
        this.$message({
          message: msg,
          type: 'success'
        })
        if (this.dialogType === 'add') {
          this.currentPage = 0
        }
        this.loadData()
      } else {
        this.$message.error(msg)
      }
    },

    async loadData() {
      let result = await this.$http.get({
        url: '/users/list'
      })
      if (result.data.ret) {
        this.tableDataList = result.data.data.reverse()
        this.total = this.tableDataList.length
      }
      this.filterData()
    },

    // 方案一：
    //post(url:/api/users/signup): signup
    //post(url:/api/users/update): update
    // 方案二： axios.fatch
    //post(url:/api/users/signup): signup
    //fetch(url:/api/users/update): update
 
    async handleSubmitClick() {
      this.$refs.upload.$refs.upload.submit()
    },

    async handleRemoveClick(index, row) {

      let result = await this.$http.removeItem({
        url: '/users/remove',
        data: JSON.stringify({id: row.id})
      })

      let msg = result.data.data.msg
      if (result.data.ret) {
        this.$message({
          message: msg,
          type: 'success'
        })
        this.loadData()
      } else {
        this.$message.error(msg)
      }
    }
  },

  async mounted() {
    this.loadData()
  },

  watch: {
    async filename(filename) {

      this.$refs['userForm'].validate(async (valid) => {
        if (valid) {
          this.dialogFormVisible = false

          let method = this.dialogType === 'add' ? 'post' : 'patch'
          let path = this.dialogType === 'add' ? '/users/signup' : '/users/update'

          let result = await this.$http[method]({
            url: path,
            data: JSON.stringify({
              ...this.form,
              filename
            })
          })

          this.handleSucc(result, path)
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
.el-button
  margin-bottom 10px
.el-pagination
  text-align right
  background #fff
  padding 10px 0
</style>